<?php

namespace App\Http\Controllers\Admin;

use App\Http\Models\Config;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;


class ConfigController extends CommonController
{
    // get admin/config
    public function index()
    {
        $config = Config::orderBy('input_type','asc')->orderBy('conf_order')->get();
        foreach($config as $item){
           switch($item->input_type){
               case 'input':
                   $item->conf_html = '<input type="text" name="conf_content['.$item->conf_id .']" class="lg" '.'value="'.$item->conf_content . '">';
                   break;
               case 'textarea':
                   $item->conf_html = '<textarea name="conf_content['.$item->conf_id.']">'.$item->conf_content.'</textarea>';
                   break;
               case 'radio':
                   //"0:关闭|1:开启"
                   $list = explode('|',$item->type_value);// ['0:关闭','1:开启']
                   $html = '';

                    foreach($list as $li){
                        //0:关闭
                        $radio = explode(':',$li); // ['0','关闭']
                        $checked = $item->conf_content == $radio[0] ? 'checked="checked"' : '';
                        $html .= '<input type="radio"' . '"'. ' name="conf_content['.$item->conf_id.']" '.$checked .' value="'.$radio[0] .'">'.$radio[1].'　';
                    }
                   $item->conf_html = $html;
                   break;
           }
        }

        return view('admin.config.index',compact('config'));
    }

    // DELETE admin/config/{id}配置项删除
    public function destroy($conf_id)
    {
        $res = Config::where('conf_id',$conf_id)->delete();
        if($res){
            $this->putFile();
            return array('status'=>0,'msg'=>'配置项删除成功!');
        }else{
            return array('status'=>1,'msg'=>'配置项删除失败!');
        }
    }

    // ajax 修改排序
    public function changeOrder()
    {
        $input = Input::all();
        $field = Config::find($input['conf_id']);
        $field->conf_order = $input['conf_order'];
        $res = $field->update();
        $data = array();
        if($res){
            $data['status'] = 0;
            $data['msg'] = '排序修改成功!';
        }else{
            $data['status'] = 1;
            $data['msg'] = '排序修改失败,请稍后再试!';

        }
        return $data;

    }

    public function checkVar()
    {
       $conf_var = Input::get('conf_var');
       $res = Config::where('conf_var',$conf_var)->get()->first();
       if($res){
          return array('status'=>1,'msg'=>'该变量名已存在!');
       }else{
          return array('status'=>0);
       }
    }

    // get admin/config/create
    public function create()
    {
        return view('admin.config.add');
    }

    // POST admin/config 入库
    public function store()
    {
        $input = Input::except('_token');
        if($input['input_type'] == 'radio'){
            $arr = explode('|',$input['type_value']);
            if(count($arr)<2){
                return back()->with('errors','添加失败! type_value格式不对!');
            };
        }
        // Validator 验证
        $rules = ['conf_title'=>'required','conf_var'=>'required','input_type'=>'required'];
        $message = ['conf_title.required'=>'配置名称不能为空!','conf_var.required'=>'变量名不能为空!','input_type.required'=>'变量类型不能为空!'];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $res = Config::create($input);
            if($res){
                $this->putFile();
                return redirect('admin/config');
            }else{
                return back()->with('errors','网站配置项添加失败!');
            }
        }else{
            return back()->withErrors($validator);
        }
    }

    // 编辑 get admin/config/{id}/edit
    public function edit($conf_id)
    {
        $field = Config::find($conf_id);
        return view('admin.config.edit',compact('field'));
    }

    // PUT|PATCH admin/config/{id} 更新分类
    public function update($conf_id)
    {
        $input = Input::except('_token','_method');
        // Validator 验证
        $rules = ['conf_title'=>'required','conf_var'=>'required','input_type'=>'required'];
        $message = ['conf_title.required'=>'名称不能为空!','conf_var.required'=>'变量名不能为空!','input_type.required'=>'类型不能为空!'];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $res = Config::where('conf_id',$conf_id)->update($input);
            if($res){
                $this->putFile();
                return redirect('admin/config');
            }else{
                return back()->with('errors','更新失败!');
            }
        }else{
            return back()->withErrors($validator);
        }

    }
    // index 页面处理内容更新
    public function contentUpdate()
    {
        $input = Input::get('conf_content');
        $status = [];
        foreach($input as $key=>$value){
           $status[] =  Config::where('conf_id',$key)->update(['conf_content'=>$value]);
        }

        if(in_array(1,$status)){
            $this->putFile();
            return back()->with('errors','修改成功!');
        }else{
            return back()->with('errors','修改失败!');
        }
    }

//    将配置写入配置文件

    // GET|HEAD admin/config/{cate} 展示单个分类信息
    public function show()
    {

    }

    //
    public function putFile()
    {
        // 从数据库获取数据
        $data = Config::pluck('conf_content','conf_var')->all();
        // 将配置内容写入文件 webconfig.php
        $path = base_path().'/config/webconfig.php';
        $str = "<?php \n". 'return '.var_export($data,true) . ';';
        $str = str_replace(['array (',')'],['[',']'],$str);
        $res = file_put_contents($path,$str);

    }

    public function test()
    {
        echo \Illuminate\Support\Facades\Config::get('webconfig.web_host');
    }

}
